package cn.tq365.service.baidu;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import cn.tq365.mapper.ChannelAccountMapper;
import cn.tq365.model.channel.struct.ChannelAccount;
import cn.tq365.model.struct.baidu.BaiduAccount;
import cn.tq365.service.channel.ChannelAccountService;
import cn.tq365.util.baidu.SyncServiceFactory;

import com.baidu.api.client.core.ClientBusinessException;
import com.baidu.api.client.core.ResHeaderUtil;
import com.baidu.api.client.core.VersionService;
import com.baidu.api.sem.common.v2.ResHeader;
import com.baidu.api.sem.sms.v2.AccountService;
import com.baidu.api.sem.sms.v2.GetAccountInfoRequest;
import com.baidu.api.sem.sms.v2.GetAccountInfoResponse;

/**
 * 百度账户服务类
 * 
 * @author lili
 * 
 */
@Service
@Scope("prototype")
public class BaiduAccountService implements ChannelAccountService {
	@Resource
	ChannelAccountMapper baiduAccountMapper;

	@Override
	public void add(ChannelAccount account) throws Exception {
		try {
			VersionService factory = SyncServiceFactory.getInstance(
					account.getName(), account.getPassword());
			AccountService service = factory.getService(AccountService.class);
			GetAccountInfoRequest parameters = new GetAccountInfoRequest();
			parameters.setType(1);
			GetAccountInfoResponse ret = service.getAccountInfo(parameters);
			ResHeader rheader = ResHeaderUtil.getResHeader(service, true);
			if (rheader.getStatus() == 0) {
				BaiduAccount ba = BaiduAccount.tranLocal(ret
						.getAccountInfoType());
				ba.setPassword(account.getPassword());
				ba.setName(account.getName());
				baiduAccountMapper.add(ba);
			} else {
				throw new ClientBusinessException(rheader, ret);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	@Override
	public void addAll() throws Exception {
	}

	/**
	 * 查询
	 * 
	 * @return
	 * @throws Exception
	 */
	// public List<BaiduAccount> query() throws Exception {
	// try {
	// return mapper.query();
	// } catch (Exception e) {
	// e.printStackTrace();
	// throw e;
	// }
	// }
}
